package com.demo.config.redis;

import com.fasterxml.jackson.databind.JavaType;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

public class CacheManagerConfig {

    public static RedisCacheConfiguration getConfig(JavaType javaType) {
        return RedisCacheConfiguration.defaultCacheConfig()
                .computePrefixWith((cacheName -> cacheName))
                .disableCachingNullValues()         //如果是空值，不缓存
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer(javaType))));
    }

    /**
     * 根据javaType将纯JSON格式的字符反序列化相应的对象
     * 如果没有javaType，纯JSON格式的字符串反序列化对象是List<LinkedHashMap>
     * @param javaType
     * @return
     */
    private static RedisSerializer<Object> valueSerializer(JavaType javaType) {
        return new Jackson2JsonRedisSerializer(javaType);
    }
}
